package com.example.musicgui.view;

import com.example.musicgui.client.AudioClient;
import com.example.musicgui.controller.MusicController;
import com.example.musicgui.model.Music;
import com.example.musicgui.tools.Audio;
import javafx.geometry.Pos;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import javafx.scene.layout.HBox;
import javafx.scene.layout.StackPane;
import javafx.scene.layout.VBox;
import javafx.scene.paint.Color;
import javafx.scene.text.Font;

import javax.sound.sampled.LineUnavailableException;
import javax.sound.sampled.UnsupportedAudioFileException;
import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RankingMusic {
    private VBox vBox;
    private Audio audio;
    private List<Music> musicList;

    public RankingMusic(){
        this.vBox = new VBox();
        vBox.setSpacing(10);
        vBox.setAlignment(Pos.CENTER);
        getMusic();
    }

    private void getMusic() {
        try {
            musicList = new MusicController().getMusic();
            for (int i = 0;i < musicList.size();i++) {
                Music music = musicList.get(i);
                HBox hBox = new HBox();
                hBox.setAlignment(Pos.CENTER);
                Label[] labels = new Label[3];

                labels[0] = new Label(music.getTitle());
                labels[1] = new Label(music.getSinger());
                labels[2] = new Label(music.getTime());

                for (int j = 0; j < 3; j++) {
                    labels[j].setPrefWidth(300);
                    labels[j].setTextFill(Color.WHITE);
                    labels[j].setFont(Font.font("Arial", 20));
                }

                HBox bto = new HBox();
                Button playButton = new Button("播放");
                Button deleteButton = new Button("删除");
                buttonActions(playButton,deleteButton,music.getUrl(),i);

                bto.getChildren().addAll(playButton, deleteButton);
                bto.setPrefWidth(80);

                hBox.getChildren().addAll(labels[0], labels[1], labels[2], bto);
                vBox.getChildren().add(hBox);
            }
        } catch (Exception e) {
            throw new RuntimeException(e);
        }

    }

    private void buttonActions(Button playButton, Button deleteButton,String url,int i) {
        ExecutorService threadPool = Executors.newFixedThreadPool(2);
        playButton.setOnAction(event -> {
               threadPool.execute(() -> {
                   if (audio != null){
                       audio.close();
                   }
                   audio = Audio.getAudio();
                   System.out.println("播放歌曲");
                   audio.audioMusicList(musicList,i);
               });
        });
    }

    public VBox getvBox() {
        return vBox;
    }
}